package com.prd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.JsonObject;
import com.prd.config.IdGeneratorSnowflake;
import com.prd.config.LoginInterceptor;
import com.prd.dto.WorkInputRecordDTO;
import com.prd.dto.WorkOrderDTO;
import com.prd.dto.WorkPointRecordDTO;
import com.prd.dto.WorkTimeNodeRecordDTO;
import com.prd.enums.WorkInputTpyeEnum;
import com.prd.enums.WorkMoudleTypeEnum;
import com.prd.enums.WorkOrderStatusEnum;
import com.prd.enums.WorkPointTypeEnum;
import com.prd.mapper.WorkInputRecordMapper;
import com.prd.mapper.WorkPointRecordMapper;
import com.prd.mapper.WorkTimeNodeRecordMapper;
import com.prd.model.*;
import com.prd.mapper.WorkOrderMapper;
import com.prd.service.WorkInputRecordService;
import com.prd.service.WorkOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.prd.service.WorkPointRecordService;
import com.prd.service.WorkTimeNodeRecordService;
import com.prd.util.CommonUtil;
import com.prd.util.JsonData;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.security.AlgorithmConstraints;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 工作单数据表 服务实现类
 * </p>
 *
 * @author lizhaoyi
 * @since 2023-10-30
 */
@Service
public class WorkOrderServiceImpl extends ServiceImpl<WorkOrderMapper, WorkOrderDO> implements WorkOrderService {

    @Autowired
    private IdGeneratorSnowflake idGeneratorSnowflake;

    private WorkOrderMapper workOrderMapper;
    private WorkPointRecordMapper workPointRecordMapper;
    private WorkInputRecordMapper workInputRecordMapper;
    private WorkTimeNodeRecordMapper workTimeNodeRecordMapper;
    private WorkPointRecordService workPointRecordService;
    private WorkTimeNodeRecordService timeNodeRecordService;
    private WorkInputRecordService inputRecordService;


    public WorkOrderServiceImpl(IdGeneratorSnowflake idGeneratorSnowflake, WorkOrderMapper workOrderMapper, WorkPointRecordMapper workPointRecordMapper, WorkInputRecordMapper workInputRecordMapper, WorkTimeNodeRecordMapper workTimeNodeRecordMapper, WorkPointRecordService workPointRecordService, WorkTimeNodeRecordService timeNodeRecordService, WorkInputRecordService inputRecordService) {
        this.idGeneratorSnowflake = idGeneratorSnowflake;
        this.workOrderMapper = workOrderMapper;
        this.workPointRecordMapper = workPointRecordMapper;
        this.workInputRecordMapper = workInputRecordMapper;
        this.workTimeNodeRecordMapper = workTimeNodeRecordMapper;
        this.workPointRecordService = workPointRecordService;
        this.timeNodeRecordService = timeNodeRecordService;
        this.inputRecordService = inputRecordService;
    }

    /**
     * 分页查询工作单
     * @param page
     * @param size
     * @return
     */
    @Override
    public Map<String, Object> page(int page, int size,Integer status,LocalDate startTime,LocalDate endTime) {
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        Page<WorkOrderDO> pageInfo = new Page<>(page,size);
        LambdaQueryWrapper<WorkOrderDO> wrapper = new LambdaQueryWrapper<WorkOrderDO>();
        wrapper.eq(WorkOrderDO::getCreatedWorkOrderId,loginUser.getId());
        if (status != null) {
            wrapper.eq(WorkOrderDO::getOrderStatus,status);
        }
        if (startTime != null && endTime != null) {
            if (startTime.isEqual(endTime)) {
                wrapper.eq(WorkOrderDO::getCreatedOrderDate,startTime);
            }else {
                wrapper.between(WorkOrderDO::getCreatedOrderDate,startTime,endTime);
            }
        }

        IPage<WorkOrderDO> workOrderDOPage = workOrderMapper.selectPage(pageInfo, wrapper);
        Map<String, Object> pageMap = new HashMap<>(3);
        pageMap.put("total_record", workOrderDOPage.getTotal());
        pageMap.put("total_page", workOrderDOPage.getPages());
        List<WorkOrderDTO> workOrderDTOList = CommonUtil.dtoListTransfer(workOrderDOPage.getRecords(), WorkOrderDTO.class);
        if (CollectionUtils.isEmpty(workOrderDTOList)) {
            pageMap.put("current_data", new ArrayList<>());
            return pageMap;
        }
        List<Long> orderIds = workOrderDTOList.stream().map(WorkOrderDTO::getId).collect(Collectors.toList());
        //转换要点记录数据
        List<WorkPointRecordDO> workPointRecordDOList = workPointRecordMapper.selectList(new LambdaQueryWrapper<WorkPointRecordDO>().in(WorkPointRecordDO::getWorkOrderId, orderIds));
        Map<Long, List<WorkPointRecordDO>> pointRecordMap = new HashMap<>(workPointRecordDOList.size());
        if (!CollectionUtils.isEmpty(workPointRecordDOList)) {
            pointRecordMap = workPointRecordDOList.stream().collect(Collectors.groupingBy(WorkPointRecordDO::getWorkOrderId));
        }
        //转换时间节点数据
        List<WorkTimeNodeRecordDO> timeNodeRecordDOS = workTimeNodeRecordMapper.selectList(new LambdaQueryWrapper<WorkTimeNodeRecordDO>().in(WorkTimeNodeRecordDO::getWorkOrderId, orderIds));
        Map<Long, List<WorkTimeNodeRecordDO>> timeNodeMap = new HashMap<>(timeNodeRecordDOS.size());
        if (!CollectionUtils.isEmpty(workPointRecordDOList)) {
            timeNodeMap = timeNodeRecordDOS.stream().collect(Collectors.groupingBy(WorkTimeNodeRecordDO::getWorkOrderId));
        }
        //转换预算记录数据
        List<WorkInputRecordDO> workInputRecordDOS = workInputRecordMapper.selectList(new LambdaQueryWrapper<WorkInputRecordDO>().in(WorkInputRecordDO::getWorkOrderId, orderIds));
        Map<Long, List<WorkInputRecordDO>> inputRecordMap = new HashMap<>(workInputRecordDOS.size());
        if (!CollectionUtils.isEmpty(workPointRecordDOList)) {
            inputRecordMap = workInputRecordDOS.stream().collect(Collectors.groupingBy(WorkInputRecordDO::getWorkOrderId));
        }

        for (WorkOrderDTO orderDTO : workOrderDTOList) {
            List<WorkPointRecordDO> pointRecordDOS = pointRecordMap.get(orderDTO.getId());
            if (!CollectionUtils.isEmpty(pointRecordDOS)) {
                orderDTO.setWorkPointRecordDTOList(CommonUtil.dtoListTransfer(pointRecordDOS,WorkPointRecordDTO.class));
            }

            List<WorkTimeNodeRecordDO> timeNodeRecordDOList = timeNodeMap.get(orderDTO.getId());
            if (!CollectionUtils.isEmpty(timeNodeRecordDOList)) {
                orderDTO.setWorkTimeNodeRecordDTOList(CommonUtil.dtoListTransfer(timeNodeRecordDOList,WorkTimeNodeRecordDTO.class));
            }
            List<WorkInputRecordDO> inputRecordDOS = inputRecordMap.get(orderDTO.getId());
            if (!CollectionUtils.isEmpty(inputRecordDOS)) {
                orderDTO.setWorkInputRecordDTOList(CommonUtil.dtoListTransfer(inputRecordDOS,WorkInputRecordDTO.class));
            }
        }
        pageMap.put("current_data", workOrderDTOList);
        return pageMap;
    }

    /**
     * 新建工作单
     * @param workOrderDTO
     * @return
     */
    @Override
    public JsonData newWordOrder(WorkOrderDTO workOrderDTO) {
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        WorkOrderDO workOrderDO = CommonUtil.dtoTransfer(workOrderDTO, WorkOrderDO.class);
        Long orderId = idGeneratorSnowflake.snowflakeId();
        if (!CollectionUtils.isEmpty(workOrderDTO.getWorkPointRecordDTOList())) {
            // TODO 相关文件上传oss文件夹，申请oss服务后再上传

            //新增工作单描述
            List<WorkPointRecordDO> workPointRecordDOList = CommonUtil.dtoListTransfer(workOrderDTO.getWorkPointRecordDTOList(), WorkPointRecordDO.class);
            for (WorkPointRecordDO workPointRecordDO : workPointRecordDOList) {
                workPointRecordDO.setWorkOrderId(orderId);
                workPointRecordDO.setModule(WorkMoudleTypeEnum.WORK_ORDER.getMessage());
                workPointRecordDO.setType(WorkPointTypeEnum.WORK_DESCRIBE.getCode());
                workPointRecordDO.setTypeName(WorkPointTypeEnum.WORK_DESCRIBE.getMessage());
                workPointRecordDO.setCreatedBy(loginUser.getName());
                workPointRecordDO.setCreatedById(loginUser.getId());
                workPointRecordDO.setCreatedTime(LocalDateTime.now());
            }
            workPointRecordService.saveBatch(workPointRecordDOList);
        }
        if (!CollectionUtils.isEmpty(workOrderDTO.getWorkTimeNodeRecordDTOList())) {
            //新增时间节点
            List<WorkTimeNodeRecordDO> timeNodeRecordDOS = CommonUtil.dtoListTransfer(workOrderDTO.getWorkTimeNodeRecordDTOList(), WorkTimeNodeRecordDO.class);
            for (WorkTimeNodeRecordDO timeNodeRecordDO : timeNodeRecordDOS) {
                timeNodeRecordDO.setWorkOrderId(orderId);
                timeNodeRecordDO.setModule(WorkMoudleTypeEnum.WORK_ORDER.getMessage());
                timeNodeRecordDO.setCreatedBy(loginUser.getName());
                timeNodeRecordDO.setCreatedById(loginUser.getId());
                timeNodeRecordDO.setCreatedTime(LocalDateTime.now());
            }
            timeNodeRecordService.saveBatch(timeNodeRecordDOS);
        }
        if (!CollectionUtils.isEmpty(workOrderDTO.getWorkInputRecordDTOList())) {
            //新增预算投入
            List<WorkInputRecordDO> inputRecordDOS = new ArrayList<>();
            List<WorkInputRecordDTO> workInputRecordDTOList = workOrderDTO.getWorkInputRecordDTOList();
            for (WorkInputRecordDTO inputRecordDTO : workInputRecordDTOList) {
                WorkInputRecordDO inputRecordDO = new WorkInputRecordDO();
                inputRecordDO.setWorkOrderId(orderId);
                inputRecordDO.setEvidence(inputRecordDTO.getEvidence().toString());
                inputRecordDO.setModule(WorkMoudleTypeEnum.WORK_ORDER.getMessage());
                inputRecordDO.setType(WorkInputTpyeEnum.PRE_INPUT.getCode());
                inputRecordDO.setCreatedBy(loginUser.getName());
                inputRecordDO.setCreatedById(loginUser.getId());
                inputRecordDO.setCreatedTime(LocalDateTime.now());
                inputRecordDO.setWorkHours(inputRecordDTO.getWorkHours());
                inputRecordDO.setPersonNum(inputRecordDTO.getPersonNum());
                inputRecordDO.setMoneyInput(inputRecordDTO.getMoneyInput());
                inputRecordDO.setGoodsInput(inputRecordDTO.getGoodsInput());
                inputRecordDO.setSourceInput(inputRecordDTO.getSourceInput());
                inputRecordDO.setRemark(inputRecordDTO.getRemark());
                inputRecordDO.setWorkContactFormId(inputRecordDTO.getWorkContactFormId());
                inputRecordDO.setWorkReportId(inputRecordDTO.getWorkReportId());
                inputRecordDOS.add(inputRecordDO);
            }
            inputRecordService.saveBatch(inputRecordDOS);

        }
        workOrderDO.setId(orderId);
        workOrderDO.setCreatedWorkOrderBy(loginUser.getName());
        workOrderDO.setCreatedWorkOrderId(loginUser.getId());
        workOrderDO.setCreatedById(loginUser.getId());
        workOrderDO.setCreatedBy(loginUser.getName());
        workOrderDO.setCreatedTime(LocalDate.now());
        workOrderDO.setCreatedOrderDate(LocalDate.now());
        workOrderDO.setOrderStatus(WorkOrderStatusEnum.DRAFT.getCode());
        int insert = workOrderMapper.insert(workOrderDO);


        return insert > 0 ? JsonData.buildSuccess() : JsonData.buildError("新增工作单异常");
    }

    /**
     * 查看工作单详情
     * @param id
     * @return
     */
    @Override
    public JsonData getDetail(Long id) {

        Long userId = LoginInterceptor.threadLocal.get().getId();
        LambdaQueryWrapper<WorkOrderDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WorkOrderDO::getId,id).eq(WorkOrderDO::getCreatedWorkOrderId,userId);
        WorkOrderDO workOrderDO = workOrderMapper.selectOne(wrapper);
        if (workOrderDO == null) {
            return JsonData.buildError("数据不存在");
        }
        WorkOrderDTO workOrderDTO = CommonUtil.dtoTransfer(workOrderDO, WorkOrderDTO.class);
        //获取要点描述
        List<WorkPointRecordDO> workPointRecordDOList = workPointRecordMapper.selectList(new LambdaQueryWrapper<WorkPointRecordDO>().eq(WorkPointRecordDO::getWorkOrderId, id));
        if (!CollectionUtils.isEmpty(workPointRecordDOList)) {
            workOrderDTO.setWorkPointRecordDTOList(CommonUtil.dtoListTransfer(workPointRecordDOList,WorkPointRecordDTO.class));
        }
        //获取决算记录
        List<WorkInputRecordDO> inputRecordDOList = workInputRecordMapper.selectList(new LambdaQueryWrapper<WorkInputRecordDO>().eq(WorkInputRecordDO::getWorkOrderId, id));
        if (!CollectionUtils.isEmpty(inputRecordDOList)) {
            List<WorkInputRecordDTO> inputRecordDTOS = new ArrayList<>();
            for (WorkInputRecordDO inputRecordDO : inputRecordDOList) {
                WorkInputRecordDTO inputRecordDTO = new WorkInputRecordDTO();
                inputRecordDTO.setId(inputRecordDO.getId());
                inputRecordDTO.setWorkHours(inputRecordDO.getWorkHours());
                inputRecordDTO.setPersonNum(inputRecordDO.getPersonNum());
                inputRecordDTO.setMoneyInput(inputRecordDO.getMoneyInput());
                inputRecordDTO.setGoodsInput(inputRecordDO.getGoodsInput());
                inputRecordDTO.setSourceInput(inputRecordDO.getSourceInput());
                inputRecordDTO.setRemark(inputRecordDO.getRemark());
                inputRecordDTO.setEvidence(Arrays.asList(inputRecordDO.getEvidence().substring(1,inputRecordDO.getEvidence().length()-1)));
                inputRecordDTO.setType(inputRecordDO.getType());
                inputRecordDTO.setModule(inputRecordDO.getModule());
                inputRecordDTO.setWorkOrderId(inputRecordDO.getWorkOrderId());
                inputRecordDTO.setWorkContactFormId(inputRecordDO.getWorkContactFormId());
                inputRecordDTO.setWorkReportId(inputRecordDO.getWorkReportId());
                inputRecordDTO.setCreatedTime(inputRecordDO.getCreatedTime());
                inputRecordDTO.setCreatedBy(inputRecordDO.getCreatedBy());
                inputRecordDTO.setCreatedById(inputRecordDO.getCreatedById());
                inputRecordDTOS.add(inputRecordDTO);
            }
            workOrderDTO.setWorkInputRecordDTOList(inputRecordDTOS);
        }
        //获取时间节点记录
        List<WorkTimeNodeRecordDO> workTimeNodeRecordDOList = workTimeNodeRecordMapper.selectList(new LambdaQueryWrapper<WorkTimeNodeRecordDO>().eq(WorkTimeNodeRecordDO::getWorkOrderId, id));
        if (!CollectionUtils.isEmpty(workTimeNodeRecordDOList)) {
            workOrderDTO.setWorkTimeNodeRecordDTOList(CommonUtil.dtoListTransfer(workTimeNodeRecordDOList, WorkTimeNodeRecordDTO.class));
        }
        return JsonData.buildSuccess(workOrderDTO);
    }

    /**
     * 获取某天某状态下的工作单记录
     * @param status
     * @return
     */
    @Override
    public JsonData getWorkOrderByDateAndStatus(Integer status,String date) {
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        List<WorkOrderDO> orderDOList = workOrderMapper.selectList(new LambdaQueryWrapper<WorkOrderDO>()
                .eq(WorkOrderDO::getOrderStatus, status)
                .eq(WorkOrderDO::getCreatedWorkOrderId, loginUser.getId())
                .eq(WorkOrderDO::getCreatedOrderDate, LocalDate.parse(date)));
        if (orderDOList.size() <= 0) {
            return JsonData.buildError("工作单记录不存在");
        }
        List<WorkOrderDTO> orderDTOList = getDetailWorkOrderDTO(orderDOList);

        return JsonData.buildSuccess(orderDTOList);
    }

    /**
     * 修改完成时间
     * @param id
     * @param time
     * @param status
     * @return
     */
    @Override
    public JsonData modifyCompleteTime(Long id, LocalDateTime time, Integer status) {

        WorkTimeNodeRecordDO workTimeNodeRecordDO = workTimeNodeRecordMapper.selectOne(new LambdaQueryWrapper<WorkTimeNodeRecordDO>()
                .eq(WorkTimeNodeRecordDO::getWorkOrderId, id)
                .eq(WorkTimeNodeRecordDO::getStatus, status)
                .eq(WorkTimeNodeRecordDO::getModule, WorkMoudleTypeEnum.WORK_ORDER.getMessage()));
        if (workTimeNodeRecordDO == null) {
            JsonData.buildError("时间节点记录为空");
        }
        workTimeNodeRecordDO.setCompledTime(time);
        int count = workTimeNodeRecordMapper.updateById(workTimeNodeRecordDO);

        return count > 0 ? JsonData.buildSuccess() : JsonData.buildError("更新数据异常");
    }

    /**
     * 撤销工作单
     * @param id
     * @return
     */
    @Override
    public JsonData cancel(Long id) {
        WorkOrderDO workOrderDO = workOrderMapper.selectOne(new LambdaQueryWrapper<WorkOrderDO>()
                .eq(WorkOrderDO::getId, id));
        if (workOrderDO == null) {
            JsonData.buildError("工作单不存在");
        }
        workOrderDO.setOrderStatus(WorkOrderStatusEnum.CANCELED.getCode());
        int count = workOrderMapper.updateById(workOrderDO);

        return count > 0 ? JsonData.buildSuccess() : JsonData.buildError("更新数据异常");
    }

    /**
     * 增加抄送人
     * @param id
     * @param userId
     * @return
     */
    @Override
    public JsonData addCCTo(Long id, Long userId) {
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        WorkOrderDO workOrderDO = workOrderMapper.selectOne(new LambdaQueryWrapper<WorkOrderDO>()
                .eq(WorkOrderDO::getId, id)
                .eq(WorkOrderDO::getCreatedWorkOrderId, loginUser.getId()));
        if (workOrderDO == null) {
            JsonData.buildError("工作单不存在");
        }

        if (workOrderDO.getCcTo() != null) {
            List<String> ccList = Arrays.asList(workOrderDO.getCcTo().split(","));
            ccList.add(String.valueOf(userId));
            String ccString = ccList.toString();
            workOrderDO.setCcTo(ccString);

        }else {
            workOrderDO.setCcTo(String.valueOf(userId));
        }

        int count = workOrderMapper.updateById(workOrderDO);

        return count > 0 ? JsonData.buildSuccess() : JsonData.buildError("增加抄送人操作异常");
    }

    /**
     * 安排执行人/由我执行
     * @param id
     * @param userId
     * @return
     */
    @Override
    public JsonData setExecutor(Long id, Long userId) {
        WorkOrderDO workOrderDO = workOrderMapper.selectOne(new LambdaQueryWrapper<WorkOrderDO>()
                .eq(WorkOrderDO::getId, id)
                .eq(WorkOrderDO::getCreatedWorkOrderId, userId));
        if (workOrderDO == null) {
            JsonData.buildError("工作单不存在");
        }

        workOrderDO.setExecutor(userId.toString());
        workOrderDO.setExecutorId(userId);

        int count = workOrderMapper.updateById(workOrderDO);

        return count > 0 ? JsonData.buildSuccess() : JsonData.buildError("安排执行人操作异常");
    }

    /**
     * 移除执行人
     * @param id
     * @return
     */
    @Override
    public JsonData cancelExecutor(Long id) {
        WorkOrderDO workOrderDO = workOrderMapper.selectOne(new LambdaQueryWrapper<WorkOrderDO>()
                .eq(WorkOrderDO::getId, id));
        if (workOrderDO == null) {
            JsonData.buildError("工作单不存在");
        }
        workOrderDO.setExecutor(null);
        workOrderDO.setExecutorId(null);
        //TODO 发送短信

        int count = workOrderMapper.updateById(workOrderDO);

        return count > 0 ? JsonData.buildSuccess() : JsonData.buildError("移除执行人操作异常");
    }

    /**
     * 预完成
     * @param id
     * @return
     */
    @Override
    public JsonData preComplete(Long id) {
        WorkOrderDO workOrderDO = workOrderMapper.selectOne(new LambdaQueryWrapper<WorkOrderDO>()
                .eq(WorkOrderDO::getId, id));
        if (workOrderDO == null) {
            JsonData.buildError("工作单不存在");
        }
        workOrderDO.setOrderStatus(WorkOrderStatusEnum.PRE_FINISHED.getCode());

        int count = workOrderMapper.updateById(workOrderDO);

        return count > 0 ? JsonData.buildSuccess() : JsonData.buildError("预完成操作异常");
    }

    /**
     * 决算
     * @param workOrderDTO
     * @return
     */
    @Override
    public JsonData finalAccount(WorkOrderDTO workOrderDTO) {

        if (workOrderDTO.getWorkInputRecordDTOList() == null) {
            return JsonData.buildError("投入记录为空");
        }

        List<WorkInputRecordDO> workInputRecordDOS = CommonUtil.dtoListTransfer(workOrderDTO.getWorkInputRecordDTOList(), WorkInputRecordDO.class);
        if (inputRecordService.saveBatch(workInputRecordDOS)) {
            return JsonData.buildSuccess();
        }else {
            return JsonData.buildError("决算操作异常");
        }

    }

    /**
     * 补充执行汇报
     * @param workOrderDTO
     * @return
     */
    @Override
    public JsonData addExecutionReport(WorkOrderDTO workOrderDTO) {
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        if (workOrderDTO.getWorkPointRecordDTO() == null) {
            JsonData.buildError("补充执行汇报传参为空");
        }

        WorkPointRecordDO workPointRecordDO = CommonUtil.dtoTransfer(workOrderDTO.getWorkPointRecordDTO(), WorkPointRecordDO.class);
        workPointRecordDO.setWorkOrderId(workOrderDTO.getId());
        workPointRecordDO.setCreatedBy(loginUser.getName());
        workPointRecordDO.setCreatedById(loginUser.getId());
        workPointRecordDO.setCreatedTime(LocalDateTime.now());
        workPointRecordDO.setModule(WorkMoudleTypeEnum.WORK_ORDER.getMessage());
        workPointRecordDO.setType(WorkPointTypeEnum.SUPPLE_EXECUTION.getCode());
        workPointRecordDO.setTypeName(WorkPointTypeEnum.SUPPLE_EXECUTION.getMessage());

        int count = workPointRecordMapper.insert(workPointRecordDO);

        return count > 0 ? JsonData.buildSuccess() : JsonData.buildError("补充执行汇报操作异常");
    }

    /**
     * 安排督导人员/由我督导
     * @param id
     * @param userId
     * @return
     */
    @Override
    public JsonData setWatcher(Long id, Long userId) {
        WorkOrderDO workOrderDO = workOrderMapper.selectOne(new LambdaQueryWrapper<WorkOrderDO>()
                .eq(WorkOrderDO::getId, id));
        if (workOrderDO == null) {
            JsonData.buildError("工作单不存在");
        }

        workOrderDO.setWorkLeaderBy(userId.toString());
        workOrderDO.setWorkLeaderId(userId);

        int count = workOrderMapper.updateById(workOrderDO);

        return count > 0 ? JsonData.buildSuccess() : JsonData.buildError("安排督导人员操作异常");
    }

    /**
     * 未达标/不合格
     * @param workOrderDTO
     * @return
     */
    @Override
    public JsonData notStandard(WorkOrderDTO workOrderDTO) {

        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        if (workOrderDTO.getWorkPointRecordDTO() == null) {
            JsonData.buildError("未达标/不合格传参为空");
        }
        WorkPointRecordDO workPointRecordDO = CommonUtil.dtoTransfer(workOrderDTO.getWorkPointRecordDTO(), WorkPointRecordDO.class);
        workPointRecordDO.setWorkOrderId(workOrderDTO.getId());
        workPointRecordDO.setCreatedBy(loginUser.getName());
        workPointRecordDO.setCreatedById(loginUser.getId());
        workPointRecordDO.setCreatedTime(LocalDateTime.now());
        workPointRecordDO.setType(WorkPointTypeEnum.NOT_STANDARD.getCode());
        workPointRecordDO.setTypeName(WorkPointTypeEnum.NOT_STANDARD.getMessage());
        workPointRecordDO.setModule(WorkMoudleTypeEnum.WORK_ORDER.getMessage());

        int count = workPointRecordMapper.insert(workPointRecordDO);

        return count > 0 ? JsonData.buildSuccess() : JsonData.buildError("未达标/不合格操作异常");
    }

    /**
     * 任务完成
     * @param id
     * @return
     */
    @Override
    public JsonData complete(Long id) {

        WorkOrderDO workOrderDO = workOrderMapper.selectOne(new LambdaQueryWrapper<WorkOrderDO>()
                .eq(WorkOrderDO::getId, id));
        if (workOrderDO == null) {
            JsonData.buildError("工作单不存在");
        }
        workOrderDO.setOrderStatus(WorkOrderStatusEnum.FINISHED.getCode());

        int count = workOrderMapper.updateById(workOrderDO);

        return count > 0 ? JsonData.buildSuccess() : JsonData.buildError("任务完成操作异常");
    }

    /**
     * 查询时间节点记录
     * @param id
     * @return
     */
    @Override
    public JsonData selectWorkTimeNodeList(Long id) {

        List<WorkTimeNodeRecordDO> timeNodeRecordDOList = workTimeNodeRecordMapper.selectList(new LambdaQueryWrapper<WorkTimeNodeRecordDO>()
                .eq(WorkTimeNodeRecordDO::getWorkOrderId, id)
                .eq(WorkTimeNodeRecordDO::getModule, WorkMoudleTypeEnum.WORK_ORDER.getMessage()));

        return JsonData.buildSuccess(CommonUtil.dtoListTransfer(timeNodeRecordDOList,WorkTimeNodeRecordDTO.class));
    }

    /**
     * 预决算意见
     * @param workOrderDTO
     * @return
     */
    @Override
    public JsonData budgetOpinion(WorkOrderDTO workOrderDTO) {
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        if (workOrderDTO.getWorkPointRecordDTO() == null) {
            JsonData.buildError("预决算意见传参为空");
        }
        WorkPointRecordDO workPointRecordDO = CommonUtil.dtoTransfer(workOrderDTO.getWorkPointRecordDTO(), WorkPointRecordDO.class);
        workPointRecordDO.setWorkOrderId(workOrderDTO.getId());
        workPointRecordDO.setCreatedBy(loginUser.getName());
        workPointRecordDO.setCreatedById(loginUser.getId());
        workPointRecordDO.setCreatedTime(LocalDateTime.now());
        workPointRecordDO.setType(WorkPointTypeEnum.BUDGET_OPINION.getCode());
        workPointRecordDO.setTypeName(WorkPointTypeEnum.BUDGET_OPINION.getMessage());
        workPointRecordDO.setModule(WorkMoudleTypeEnum.WORK_ORDER.getMessage());

        int count = workPointRecordMapper.insert(workPointRecordDO);

        return count > 0 ? JsonData.buildSuccess() : JsonData.buildError("预决算意见操作异常");
    }

    /**
     * 获取所有记录数据并组装工作单DTO
     * @param orderDOList
     * @return
     */
    private List<WorkOrderDTO> getDetailWorkOrderDTO(List<WorkOrderDO> orderDOList) {

        List<WorkOrderDTO> orderDTOList = CommonUtil.dtoListTransfer(orderDOList, WorkOrderDTO.class);

        Map<Long, List<WorkOrderDTO>> orderDTOMap = orderDTOList.stream().collect(Collectors.groupingBy(WorkOrderDTO::getId));

        List<Long> orderIdList = orderDTOMap.keySet().stream().collect(Collectors.toList());

        //获取要点描述
        List<WorkPointRecordDO> workPointRecordDOList = workPointRecordMapper.selectList(new LambdaQueryWrapper<WorkPointRecordDO>().in(WorkPointRecordDO::getWorkOrderId, orderIdList));
        Map<Long, List<WorkPointRecordDO>> pointRecordMap = workPointRecordDOList.stream().collect(Collectors.groupingBy(WorkPointRecordDO::getWorkOrderId));
        for (Long pointKey : pointRecordMap.keySet()) {
            for (Long orderKey : orderDTOMap.keySet()) {
                List<WorkPointRecordDO> workPointRecordDOS = pointRecordMap.get(orderKey);
                if (workPointRecordDOS != null) {
                    List<WorkPointRecordDTO> pointRecordDTOList = CommonUtil.dtoListTransfer(workPointRecordDOS, WorkPointRecordDTO.class);
                    orderDTOMap.get(pointKey).get(0).setWorkPointRecordDTOList(pointRecordDTOList);
                }
            }
        }
        //获取决算记录
        List<WorkInputRecordDO> inputRecordDOList = workInputRecordMapper.selectList(new LambdaQueryWrapper<WorkInputRecordDO>().in(WorkInputRecordDO::getWorkOrderId, orderIdList));
        Map<Long, List<WorkInputRecordDO>> inputRecordMap = inputRecordDOList.stream().collect(Collectors.groupingBy(WorkInputRecordDO::getWorkOrderId));
        for (Long inputKey : inputRecordMap.keySet()) {
            for (Long orderKey : orderDTOMap.keySet()) {
                List<WorkInputRecordDO> workInputRecordDOS = inputRecordMap.get(orderKey);
                if (workInputRecordDOS != null) {
                    List<WorkInputRecordDTO> workInputRecordDTOList = CommonUtil.dtoListTransfer(workInputRecordDOS, WorkInputRecordDTO.class);
                    orderDTOMap.get(inputKey).get(0).setWorkInputRecordDTOList(workInputRecordDTOList);
                }
            }
        }
        //获取时间节点记录
        List<WorkTimeNodeRecordDO> workTimeNodeRecordDOList = workTimeNodeRecordMapper.selectList(new LambdaQueryWrapper<WorkTimeNodeRecordDO>().in(WorkTimeNodeRecordDO::getWorkOrderId, orderIdList));
        Map<Long, List<WorkTimeNodeRecordDO>> timeNodeMap = workTimeNodeRecordDOList.stream().collect(Collectors.groupingBy(WorkTimeNodeRecordDO::getWorkOrderId));
        for (Long timeNodeKey : timeNodeMap.keySet()) {
            for (Long orderKey : orderDTOMap.keySet()) {
                List<WorkTimeNodeRecordDO> timeNodeRecordDOS = timeNodeMap.get(orderKey);
                if (timeNodeRecordDOS != null) {
                    List<WorkTimeNodeRecordDTO> timeNodeRecordDTOList = CommonUtil.dtoListTransfer(timeNodeRecordDOS, WorkTimeNodeRecordDTO.class);
                    orderDTOMap.get(timeNodeKey).get(0).setWorkTimeNodeRecordDTOList(timeNodeRecordDTOList);
                }
            }
        }

        List<WorkOrderDTO> workOrderDTOList = new ArrayList<>(orderDTOMap.values().size());
        for (List<WorkOrderDTO> workOrderDTOS : orderDTOMap.values()) {
            workOrderDTOList.add(workOrderDTOS.get(0));
        }

        return workOrderDTOList;
    }


    private WorkOrderDTO do2Dto(WorkOrderDO workOrderDO) {
        WorkOrderDTO workOrderDTO = new WorkOrderDTO();
        BeanUtils.copyProperties(workOrderDO, workOrderDTO);
        return workOrderDTO;
    }
}
